import axios from 'axios'
import vueCookie from 'vuecookie'
import { Toast } from 'vant'

// const baseUrl = process.env.VUE_APP_DOMAIN_URL
const baseUrl = '/'
const timeOut = process.env.VUE_APP_TIME_OUT
const TokenName = process.env.VUE_APP_TOKEN_NAME || 'token'

const config = axios.create({
  baseURL: baseUrl,
  timeout: timeOut || 5000
})

config.interceptors.request.use((con) => {
  const author = JSON.parse(localStorage.getItem(TokenName)) || vueCookie.get(TokenName)
  if (author) {
    con.headers.common['Authorization'] = author
  }
  if (con.isLoading) {
    Toast.loading({
      message: '拼命加载中...',
      forbidClick: true,
      loadingType: 'spinner'
    })
  }
  if (con.method === 'post') {
    con.headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
      // 'Content-Type': 'application/json;charset=utf-8'
    }
  }
  return con
},
  (error) => {
    return Promise.reject(error)
  }
)

config.interceptors.response.use(
  (res) => {
    Toast.clear()
    if (res.status && res.status !== 200 && res.status > 400) {
      switch (res.status) {
        case 401:
          Toast.fail('请重新登录')
          break
        case 402:
          Toast.fail('您无权限操作！')
          break
        case 403:
          Toast.fail('您无权限操作！')
          break
        default:
          Toast.fail('网络错误，请重试')
      }
    }
    return res
  },
  (err) => {
    Toast.clear()
    return Promise.reject(err)
  }
)

export default config
